package com.xquant.databasemanagement.controller.panel.center;

import com.xquant.databasemanagement.bean.CommonObject;
import com.xquant.databasemanagement.controller.FormController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;

import java.net.URL;
import java.util.ResourceBundle;

public class CommonPanelController implements Initializable, FormController {

    @FXML
    private VBox commonPanel;
    @FXML
    private TextArea oracle;
    @FXML
    private TextArea mySQL;
    @FXML
    private TextField name;

    private CommonObject commonBean = null;

    private TreeItem treeItem = null;

    private TreeView treeView;


    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }




    @Override
    public void clear(){
        commonBean = null;
        treeItem = null;
        name.clear();
        oracle.clear();
        mySQL.clear();
    }

    @Override
    public boolean isValid() {
        if ("".equals(oracle.getText().replace(" ",""))){
            new Alert(Alert.AlertType.NONE, "请输入对于的oracle语句", new ButtonType[]{ButtonType.CLOSE}).show();
            return false;
        }else if ("".equals(mySQL.getText().replace(" ",""))){
            new Alert(Alert.AlertType.NONE, "请输入对于的MySQL语句", new ButtonType[]{ButtonType.CLOSE}).show();
            return false;
        }else if (!name.getText().matches("^\\w+$")) {
            new Alert(Alert.AlertType.NONE, "字段命名不正确", new ButtonType[]{ButtonType.CLOSE}).show();
            return false;
        }
        return true;
    }

    @FXML
    private void actionSaveButton(ActionEvent event) {
        if (isValid()) {
            setCommonBean();
            if (this.treeItem != null) {
                treeItem.getChildren().add(new TreeItem(this.commonBean));
            } else
                treeView.refresh();
            clear();
            ((BorderPane) commonPanel.getParent()).setCenter(null);
        }

    }

    public void setTreeItem(TreeItem treeItem){
        this.treeItem = treeItem;
    }


    public void setCommonBean(CommonObject commonBean ){
        this.commonBean = commonBean;
        name.setText(commonBean.getName());
        oracle.setText(commonBean.getOracleSQL());
        mySQL.setText(commonBean.getMySQL());
    }


    public void setCommonBean(){
        if (this.commonBean == null)
            this.commonBean = new CommonObject();
        this.commonBean.setName(name.getText());
        this.commonBean.setMySQL(mySQL.getText());
        this.commonBean.setOracleSQL(oracle.getText());

    }

    public void setTreeView(TreeView treeView){
        this.treeView = treeView;
    }
}
